<template>
  <view class="WeChatAuthorization">
    <u-button :custom-style="customStyle"
              @click="handleLgoin">授权微信登录</u-button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      customStyle: {
        color: '#fff',
        width: '641rpx',
        height: '88rpx',
        backgroundColor: '#07C160',
      },
    }
  },
  methods: {
    async handleLgoin() {
      const [err, userInfo] = await uni.getUserProfile({ desc: '小小怪' })
      const {
        encryptedData,
        rawData,
        iv,
        signature,
        userInfo: { avatarUrl },
      } = userInfo
      const [codeError, codeMsg] = await uni.login({ timeout: 50000 })
      if (codeError !== null) {
        wx.showToast({
          title: '状态码超时',
          icon: 'none',
        })
        return false
      }
      const { code } = codeMsg
      const data = { encryptedData, rawData, iv, signature, code }
      let flag = false
      for (const key in data) {
        if (!data[key]) {
          flag = true
        }
      }
      if (flag) {
        uni.showToast({
          title: '没有获取用户信息',
          icon: 'none',
        })
      } else {
        flag = false
        const userData = await this.$u.post('/users/wxlogin', data)
        userData.avatarUrl = avatarUrl
        this.$store.commit('user/setToken', userData)
        wx.switchTab({url: '/pages/my/my'});
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.WeChatAuthorization {
  position: relative;
  height: 100vh;
  u-button {
    position: absolute;
    top: 30%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>